package com.richmond.gui;

import com.richmond.data.TimeRecord;
import com.richmond.data.Workday;
import com.richmond.util.TimeSheetParser;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.FileChooser;
import javafx.util.Callback;
import javafx.util.Duration;
import org.apache.log4j.Logger;
import sun.awt.windows.ThemeReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.prefs.Preferences;

/**
 * User: csavard
 * Date: 12-08-07
 * Time: 17:36
 */
public class AccountUtilController implements Initializable {
    private Logger logger = Logger.getLogger(AccountUtilController.class);

    @FXML
    private AnchorPane root;

    @FXML
    private Node lockPane;

    @FXML
    private ListView list;

    @FXML
    private TableView table;

    @FXML
    private TableColumn noCol;

    @FXML
    private TableColumn nameCol;

    @FXML
    private TableColumn codeCol;

    @FXML
    private TableColumn descriptionCol;

    @FXML
    private TableColumn bonusCol;

    @FXML
    private TableColumn regularCol;

    @FXML
    private Label workdayLabel;

    private Workday selectedWorkday;
    private final ExecutorService executorService = new ScheduledThreadPoolExecutor(1);

    public void open(ActionEvent event) {
        String initialDirectory = Preferences.userRoot().get("initialDirectory", null);
        FileChooser fileChooser = new FileChooser();
        if (initialDirectory != null) {
            fileChooser.setInitialDirectory(new File(initialDirectory));
        }

        final File file = fileChooser.showOpenDialog(root.getScene().getWindow());
        if (file != null) {
            Task task = new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    try {
                       /* final FadeTransition fadeTransition = new FadeTransition(Duration.millis(250), lockPane);
                        fadeTransition.setFromValue(0.0f);
                        fadeTransition.setToValue(0.75f);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                lockPane.setVisible(true);
                                fadeTransition.play();
                            }
                        });*/

                        LockPane.lock(root);

                        Thread.sleep(250);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                list.getItems().clear();
                            }
                        });
                        Thread.sleep(500);

                        Preferences.userRoot().put("initialDirectory", file.getParentFile().getAbsolutePath());
                        logger.info("File: " + file.getAbsolutePath());
                        final List<Workday> workdays = TimeSheetParser.parse(new FileInputStream(file));
                        for (final Workday workday : workdays) {
                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    list.getItems().add(workday);
                                }
                            });

                            Thread.sleep(25);
                        }

                        Thread.sleep(100);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                list.getSelectionModel().select(0);
                            }
                        });

                       /* Thread.sleep(500);
                        fadeTransition.setFromValue(0.75f);
                        fadeTransition.setToValue(0.0f);

                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                fadeTransition.play();
                            }
                        });

                        Thread.sleep(500);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                lockPane.setVisible(false);
                            }
                        });*/
                    } catch (Exception e) {
                        logger.error(null, e);
                    }
                    return null;
                }
            };

            executorService.execute(task);
        }
    }

    @Override
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

        list.getSelectionModel().selectedItemProperty().addListener(new WorkdayChangeListener());
        list.setCellFactory(new ListViewWordayListCellCallback());

        noCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, Long>("workerNo"));
        nameCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, String>("name"));
        codeCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, String>("code"));
        descriptionCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, String>("codeDescription"));
        bonusCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, Float>("bonus"));
        regularCol.setCellValueFactory(new PropertyValueFactory<TimeRecord, Float>("regular"));
    }

    private static class ListViewWordayListCellCallback implements Callback<ListView<Workday>, WordayListCell> {

        @Override
        public WordayListCell call(ListView<Workday> workdayListView) {
            return new WordayListCell();
        }
    }

    private class WorkdayChangeListener implements ChangeListener<Workday> {
        @Override
        public void changed(ObservableValue<? extends Workday> observableValue, Workday workday, final Workday workday1) {
            selectedWorkday = workday1;
            table.getItems().clear();
            if (workday1 != null) {
                final ObservableList<TimeRecord> timeRecords = FXCollections.observableArrayList(workday1.getTimeRecords());
                table.setItems(timeRecords);

                workdayLabel.setText(WordayListCell.DATE_FORMAT.format(workday1.getDate()) + "	(" + workday1.getTimeRecords().size() + " entrées)");
            } else {
                workdayLabel.setText("Aucune journée selectionnée");
            }
        }
    }
}
